package pl.mw.cmd.internal.telnetserver;

import org.jboss.netty.channel.Channel;

import pl.mw.cmd.greeting.Greeting;
import pl.mw.cmd.telnetserver.MessageReceiver;
import pl.mw.cmd.telnetserver.ReplaySender;

/**
 * Serwer telnet.
 */
public class TelnetServer extends BaseTelnetServer {
	
	/** Odpowiada za odbior komunikatow */
	private MessageReceiver receiver;
	
	/**
	 * Tworzy komponent serwera telnet.
	 */
	public TelnetServer() {
		System.out.println("[pl.mw.cmd.telnetserver] [TelnetServer] Component created.");
	}
	
	/**
	 * Ustawia interpreter komend.
	 * @param commandInterpreter interpreter komend
	 */
	public void setReceiver(MessageReceiver receiver) {
		this.receiver = receiver;
		
		System.out.println("[pl.mw.cmd.telnetserver] [TelnetServer] receiver bound.");
	}
	
	/**
	 * Wylacza ssinterpreter komend.
	 * @param commandInterpreter interpreter komend
	 */
	public void unsetReceiver(MessageReceiver receiver) {
		this.receiver = null;
		
		System.out.println("[pl.mw.cmd.telnetserver] [TelnetServer] receiver unbound.");
	}
	
	/**
	 * Startuje serwer telnet.
	 */
	public void start() {
		super.start();
		System.out.println("[pl.mw.cmd.telnetserver] [TelnetServer] Component activated.");
	}
	
	/**
	 * Zatrzymuje serwer telnet.
	 */
	public void stop() {
		super.stop();
		System.out.println("[pl.mw.cmd.telnetserver] [TelnetServer] Component deactivated.");
	}
	
	/**
	 * {@inheritDoc}
	 * 
	 * @see BaseTelnetServer#channelConnected(Channel)
	 */
	@Override
	protected void channelConnected(ReplaySender replaySender) {
		String msg = Greeting.getGreetingMessage();
		replaySender.send(msg + "\r\n> ");
	}
	
	/**
	 * {@inheritDoc}
	 * 
	 * @see BaseTelnetServer#messageReceived(String, Channel)
	 */
	@Override
	protected void messageReceived(String message, ReplaySender replaySender) {
		if (message.trim().toLowerCase().equals("bye")) {
			replaySender.send("Do zobaczenia.\r\n");
			replaySender.close();
		} else if (this.receiver == null) {
			replaySender.send("Interpreter polecen nie jest dostepny.\r\n> ");
		} else {
			this.receiver.messageReceived(message, replaySender);
		} 
	}
}
